<?php
namespace app\account\controller;

use tp5_lib\common\controller\BaseController;
use tp5_lib\account\model\RechargeModel;
use tp5_lib\user\model\UserModel;
use tp5_lib\account\logic\AccountModule;
use tp5_lib\account\logic\AccountLogic;

class IndexController extends BaseController
{
    public function index()
    {
        $user=$this->checkPrivilege("account.mine");
        $model=new UserModel();
        $user=$model->db()->where(["id"=>$user["id"]])->find();
        $this->assign("user",$user);
        return $this->fetch();
    }
    /**
     * 充值
     */
    public function recharge()
    {
        $module=new AccountModule();
        if(!$config=$module->read("account")){
            $this->error("配置文件丢失");
        }
        $this->assign("payment",$config["payment"]);
        
        return $this->fetch();
    }
    public function doRecharge()
    {
        $user=$this->checkLogin();
        if(!$amount=input("amount")){
            $this->error("充值金额不能为空");
        }
        if(!$way=input("way")){
            $this->error("支付方式不能为空");
        }
        $data=[
            "user_id"=>$user["id"],
            "amount"=>$amount,
            "time"=>time(),
        ];
        $model=new RechargeModel();
        if(!$id=$model->db()->insertGetId($data)){
            $this->error("创建失败");
        }

        $module=new AccountModule();
        if(!$config=$module->read("account")){
            $this->error("配置文件丢失");
        }
        if(empty($config["payment"][$way])){
            $this->error("未定义的支付方式");
        }
        $payment=$config["payment"][$way];
        $class=$payment["class"];
        /** @var Payment $object */
        $object=new $class;
        $object->precreate("recharge-$id",$amount,"充值");
    }
    /**
     * 提现
     */
    public function withdraw()
    {
        return $this->fetch();
    }
    public function doWithdraw()
    {
        $user=$this->checkLogin();
        if(!$amount=input("amount")){
            $this->error("提现金额不能为空");
        }
        if(!$way=input("way")){
            $this->error("提现方式不能为空");
        }

        $module=new AccountModule();
        if(!$config=$module->read("account")){
            $this->error("配置文件丢失");
        }
        if(empty($config["payment"][$way])){
            $this->error("未定义的支付方式");
        }

        $logic=new AccountLogic();
        if(!$logic->withdraw($user["id"],$amount,$way)){
            $this->error($logic->getError());
        }
        $this->success("提交成功，请等待审核");
    }
}
